from jsonpath import jsonpath
from requests import Response

from ...base.base_api import BaseApi


class Department(BaseApi):
    def __init__(self):
        super().__init__()
        self.token = self.get_token_by_file()

    def create_department(self, data) -> Response:
        """
        创建部门
        请求方式：POST（HTTPS）
        请求地址：https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=ACCESS_TOKEN
        @rtype: Response
        """
        url = self.base_url + f"/cgi-bin/department/create?access_token={self.token}"
        req = {
            "method": "POST",
            "url": url,
            "json": data
        }
        r = self.send(req)
        return r

    def update_department(self, data) -> Response:
        """
        更新部门
        请求方式：POST（HTTPS）
        请求地址：https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token=ACCESS_TOKEN
        @rtype: Response
        """
        url = self.base_url + f"/cgi-bin/department/update?access_token={self.token}"
        req = {
            "method": "POST",
            "url": url,
            "json": data
        }
        r = self.send(req)
        return r
        pass

    def delete_department(self, department_id) -> Response:
        """
        删除部门
        请求方式：GET（HTTPS）
        请求地址：https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token=ACCESS_TOKEN&id=ID
        @rtype: Response
        """
        url = self.base_url + f"/cgi-bin/department/delete"
        params = {
            "access_token": self.token,
            "id": department_id
        }
        req = {
            "method": "POST",
            "url": url,
            "params": params
        }
        r = self.send(req)
        return r

    def get_department_ids(self, department_id=None) -> Response:
        """
        获取部门ID列表
        请求方式：GET（HTTPS）
        请求地址：https://qyapi.weixin.qq.com/cgi-bin/department/simplelist?access_token=ACCESS_TOKEN&id=ID
        @rtype: Response
        """
        url = self.base_url + f"/cgi-bin/department/simplelist"
        params = {
            "access_token": self.token,
            "id": department_id
        }
        req = {
            "method": "GET",
            "url": url,
            "params": params
        }
        r = self.send(req)
        return r

    def clear(self):
        """
        除了主部门，其他部门都要清理
        @rtype: object
        """
        r = self.get_department_ids()
        ids = jsonpath(r.json(), "$.[?(@.parentid>0)].id")
        if ids:
            for i in ids:
                self.delete_department(i)
